//
//  PHOAuthViewController.swift
//  PHWeibo
//
//  Created by 潘荟 on 16/7/20.
//  Copyright © 2016年 BAT. All rights reserved.
//

import UIKit
import SVProgressHUD

class PHOAuthViewController: UIViewController {
    
    override func loadView() {
        //接口url
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREDIRECT_URI)"
        
        let url = NSURL(string: urlStr)
        
        guard let u = url else {
            return
        }
        
        let request = NSURLRequest(URL: u)
        
        webView.loadRequest(request)
        
        webView.delegate = self
        
        view = webView
    }
    


    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
    }
    
    // MARK: - 实现监听方法
    @objc private func cancelClick() {
        dismissViewControllerAnimated(true, completion: nil)

    }
    
    @objc private func autofillClick() {
        let jsStr = "document.getElementById('userId').value = '\(weiboName)',document.getElementById('passwd').value = '\(weiboPassword)'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsStr)
    }
    
    private func setupUI() {
        view.backgroundColor = UIColor.whiteColor()
        
        navigationController?.view.insertSubview(progressView, aboveSubview: navigationController!.navigationBar)
//        view.insertSubview(progressView, belowSubview: view)
        
//        view ,view1,view2
//        view.insertSubview(view2, belowSubview: view1)

        view.addSubview(progressView)
//        print(view.subviews.count)
        
        setupNav()
        
    }
    
    private func setupNav() {
        navigationItem.title = "微博登陆"

        
        navigationItem.leftBarButtonItem = PHBarButtonItem(title: "取消", imgName: nil, target: self, action: "cancelClick")
        navigationItem.rightBarButtonItem = PHBarButtonItem(title: "自动填充", imgName: nil, target: self, action: "autofillClick")
        
        
    }
    
    // MARK: - 懒加载控件
    lazy var webView:UIWebView = UIWebView()
    
    lazy var progressView:PHProgressView = PHProgressView()
    
    
    deinit {
        print("3333")
    }

}


extension PHOAuthViewController:UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        progressView.startAnim()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        progressView.endAnim()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlStr = request.URL?.absoluteString
        
//        print("\(urlStr)")
        
        if let u = urlStr where u.hasPrefix(APPREDIRECT_URI) {
            let query = request.URL?.query
//            print("\(query)")
            
            if let q = query {
                let code = q.substringFromIndex("code=".endIndex)
                
                PHUserAccountView.sharedTools.getUserAccount(code, isSuccess: { (isSucc) -> () in
                    if !isSucc {
                        print("请求失败")
                        return
                    }
                    
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNoti, object: nil)
                    })
                })
                
            }
        }
        
        return true
    }
}

//MARK - 请求数据
//extension PHOAuthViewController {
//    //请求accessToken数据
//    func getUserAccount(code:String) {
//        PHNetworktools.sharedTools.oauthLoadUserAccount(code, success: { (response) -> () in
//            
//            guard let res = response as? [String : AnyObject] else {
//                return
//            }
//            
//            let userAccount = PHUserAccount(dict: res)
//            
//            self.getUserInfo(userAccount)
//            
//            }) { (error) -> () in
//                print("请求失败:\(error)")
//        }
//    }
//    
//    
//    
//    //请求用户信息数据
//    func getUserInfo(userAccount : PHUserAccount) {
//        PHNetworktools.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) -> () in
//            guard let res = response as? [String : AnyObject] else {
//                return
//            }
//            
//            userAccount.screen_name = res["screen_name"] as? String
//            userAccount.avatar_large = res["avatar_large"] as? String
//            
//            }) { (error) -> () in
//                print("请求失败:\(error)")
//        }
//    }
//}







